package com.wmz.gulimall.product.exception;

import com.wmz.common.exception.BizCodeEnum;
import com.wmz.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


/**
 * @author wmz
 * @date 2024/7/27 11:15
 * @description 全局异常处理类
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.wmz.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    /**
     * 处理数据校验错误
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        Map<String,String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        // 获取校验的错误结果
        result.getFieldErrors().forEach((item) -> {
            // FieldError 获取到错误提示
            String message = item.getDefaultMessage();
            // 获取错误的属性的名字
            String field = item.getField();
            map.put(field,message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
